// const baseUrl = 'https://aqueous-retreat-34523.herokuapp.com'	//heroku线上
const baseUrl = 'http://120.25.100.200:3000'	//阿里线上
// const baseUrl = 'http://localhost:3000'		//本地
function toast(title) {
	return uni.showToast({
		title,
		icon: 'none'
	})
}

// 请求完成时处理结果
function result(resp, resolve, reject) {
	// console.log(resp)
	if (resp && resp != "") {
		//请求状态码
		var statusCode = resp.statusCode;
		if (statusCode != 200) {
			console.log(resp)
			let _msg = resp.data.msg;
			if (_msg == undefined || _msg == "") {
				_msg = "服务出错：500"
			}
			toast(_msg)
			reject(resp.data.msg);
		} else if(statusCode == 200) {
			var result;
			if (typeof(resp.data) == "string") {
				////返回的结果为string，parse一下
				result = JSON.parse(resp.data);
			} else {
				result = resp.data;
			}
			var status = "";
			if (result.code != undefined) {
				status = result.code;
			}
			var message = "";
			if (result.message) {
				message = result.message;
			}
			if (status == 200) {
				var data = "";
				if (result.data) {
					data = result.data;
				} else {
					data = result
				}
				resolve({
					status,
					message,
					data
				})
			} else {
				toast(message);
				reject({
					status,
					message
				});
			}
		}
	}
}

// 发送请求
export function request(method, url, data) {
	var p = new Promise((resolve, reject) => {
		uni.request({
			url: baseUrl + url, //仅为示例，并非真实接口地址。
			data: data,
			header: {
			    'token': uni.getStorageSync('token'), //自定义请求头信息
				'cookie': uni.getStorageSync('cookie')
			},
			method: method,
			success: (res) => {
				result(res, resolve, reject)
			},
			fail(err) {
				var errMsg = "";
				if (err != undefined && err.errMsg != undefined) {
					errMsg = err.errMsg;
				}
				toast("连接失败：服务器出错:" + errMsg);
				console.log(err)
				reject(err.errMsg);
			}
		});
	})
	return p
}
